package luongvd.weather.model.dbhelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import luongvd.weather.model.object.ObjectCity;
import luongvd.weather.model.object.ObjectForecast;
import luongvd.weather.model.object.ObjectWeather;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHandler extends SQLiteOpenHelper{

	private static SQLiteDatabase mDataBase;
	private Context mContext;
	public static String DB_PATH;
	
	public DatabaseHandler(Context context) {
		super(context, DBDefinition.DATABASE_NAME, null, DBDefinition.DATABASE_VERSION);										
		this.mContext = context;
		DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
	}

	// Open the database, so we can query it
	public static boolean openDataBase() throws SQLException {
		String mPath = DB_PATH + DBDefinition.DATABASE_NAME;
		mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
		return mDataBase != null;
	}
	
	public void createDataBase() throws IOException {
		// If database not exists copy it from the assets
		boolean mDataBaseExist = checkDataBase();
		if (!mDataBaseExist) {
			Log.d("Luong", "============== khong ton tai db");
			this.getReadableDatabase();
			this.close();
			try {
				copyDataBase();
			} catch (Exception e) {
				Log.d("Luong", "============== Loi copy db");
			}
		}else{
			Log.d("Luong", "============== da ton tai db");
		}
	}
	
	private boolean checkDataBase() {
		SQLiteDatabase mCheckDataBase = null;
		boolean isExits = false;
		try {
			String outFileName = DB_PATH + DBDefinition.DATABASE_NAME;
			File createOutFile = new File(outFileName);
			if (!createOutFile.exists()) {
			}else{
				isExits = true;
				mCheckDataBase = SQLiteDatabase.openDatabase(outFileName, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
			}
		} catch (SQLiteException mSQLiteException) {
		}

		if (mCheckDataBase != null) {
			mCheckDataBase.close();
		}
		return isExits;
	}
	
	// add row in table weather
	public static boolean addWeather(String dt, String date_city, String name_city, String icon,
			String temp, String temp_max, String temp_min, String humidity, String description) {
		try {
			openDataBase();
			ContentValues initialValues = new ContentValues();
			initialValues.put(DBDefinition.COLUMN_DT, dt);
			initialValues.put(DBDefinition.COLUMN_DATE_CITY, date_city);
			initialValues.put(DBDefinition.COLUMN_NAME_CITY, name_city);
			initialValues.put(DBDefinition.COLUMN_ICON, icon);
			initialValues.put(DBDefinition.COLUMN_TEMP, temp);
			initialValues.put(DBDefinition.COLUMN_TEMP_MAX, temp_max);
			initialValues.put(DBDefinition.COLUMN_TEMP_MIN, temp_min);
			initialValues.put(DBDefinition.COLUMN_HUMIDITY, humidity);
			initialValues.put(DBDefinition.COLUMN_DESCRIPTION, description);
			mDataBase.insert(DBDefinition.TABLE_WEATHER, null, initialValues);
			mDataBase.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	// add row in table forecast
	public static boolean addForecast(String dt, String name_city, String day_of_week,
			String day_of_month, String icon, String temp_max, String temp_min) {
		try {
			openDataBase();
			ContentValues initialValues = new ContentValues();
			initialValues.put(DBDefinition.COLUMN_DT, dt);
			initialValues.put(DBDefinition.COLUMN_NAME_CITY, name_city);
			initialValues.put(DBDefinition.COLUMN_ICON, icon);
			initialValues.put(DBDefinition.COLUMN_DAY_OF_WEEK, day_of_week);
			initialValues.put(DBDefinition.COLUMN_TEMP_MAX, temp_max);
			initialValues.put(DBDefinition.COLUMN_TEMP_MIN, temp_min);
			initialValues.put(DBDefinition.COLUMN_DAY_OF_MONTH, day_of_month);
			mDataBase.insert(DBDefinition.TABLE_FORECAST, null, initialValues);
			mDataBase.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	// add row in table forecast
	public static boolean addWeatherView(String name_city, String time_update) {
		try {
			openDataBase();
			ContentValues initialValues = new ContentValues();
			initialValues.put(DBDefinition.COLUMN_NAME_CITY, name_city);
			initialValues.put(DBDefinition.COLUMN_TIME_UPDATE, time_update);
			mDataBase.insert(DBDefinition.TABLE_WEATHER_VIEW, null, initialValues);
			mDataBase.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	// delete row in table weather
	public static Boolean deleteRowWeatherView() {
		try {
			openDataBase();
			mDataBase.delete(DBDefinition.TABLE_WEATHER_VIEW, null, null);
			mDataBase.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	// delete row in table weather
	public static Boolean deleteRowWeather(String id) {
		try {
			openDataBase();
			mDataBase.delete(DBDefinition.TABLE_WEATHER, "id ='" + id + "'", null);
			mDataBase.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	// delete row in table weather
	public static Boolean deleteRowWeatherByName(String name) {
		try {
			openDataBase();
			mDataBase.delete(DBDefinition.TABLE_WEATHER, "name_city ='" + name + "'", null);
			mDataBase.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	// delete row in table forecast
	public static Boolean deleteRowForecastByName(String name) {
		try {
			openDataBase();
			mDataBase.delete(DBDefinition.TABLE_FORECAST, "name_city ='" + name + "'", null);
			mDataBase.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	// delete row in table forecast
	public static Boolean deleteRowForecast(String id_weather) {
		try {
			openDataBase();
			mDataBase.delete(DBDefinition.TABLE_WEATHER, "id_weather ='" + id_weather + "'", null);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	// view info in table weather
	public ArrayList<ObjectWeather> getInfoWeatherAllLocation() {
		ArrayList<ObjectWeather> arrayProject = new ArrayList<ObjectWeather>();
		String sql = "SELECT * FROM '" + DBDefinition.TABLE_WEATHER + "'";
		try {
			openDataBase();
			Cursor mCursor = mDataBase.rawQuery(sql, null);
			if (mCursor != null && mCursor.moveToFirst()) {
				do {
					String dt = mCursor.getString(8);
					String date_city = mCursor.getString(9);
					String id = mCursor.getString(0);
					String name_city = mCursor.getString(1);
					String icon_weather = mCursor.getString(2);
					String temp = mCursor.getString(3);
					String temp_max = mCursor.getString(4);
					String temp_min = mCursor.getString(5);
					String humidity = mCursor.getString(6);
					String description_weather = mCursor.getString(7);

					ObjectWeather objectProject = new ObjectWeather();
					objectProject.setDt_weather(dt);
					objectProject.setDate_city(date_city);
					objectProject.setId(id);
					objectProject.setName_city(name_city);
					objectProject.setIcon_weather(icon_weather);
					objectProject.setTemp(temp);
					objectProject.setTemp_max(temp_max);
					objectProject.setTemp_min(temp_min);
					objectProject.setHumidity(humidity);
					objectProject.setDescription_weather(description_weather);

					arrayProject.add(objectProject);
				} while (mCursor.moveToNext());
			}
			mCursor.close();
			mDataBase.close();
		} catch (Exception e) {
		}
		return arrayProject;
	}
	
	// view info in table weather
	public ArrayList<ObjectWeather> getInfoWeather(String name_city_input) {
		ArrayList<ObjectWeather> arrayProject = new ArrayList<ObjectWeather>();
		String sql = "SELECT * FROM '" + DBDefinition.TABLE_WEATHER + "' WHERE name_city = '" + name_city_input+"'";
		try {
			openDataBase();
			Cursor mCursor = mDataBase.rawQuery(sql, null);
			if (mCursor != null && mCursor.moveToFirst()) {
				do {
					String dt = mCursor.getString(9);
					String date_city = mCursor.getString(0);
					String id = mCursor.getString(1);
					String name_city = mCursor.getString(2);
					String icon_weather = mCursor.getString(3);
					String temp = mCursor.getString(4);
					String temp_max = mCursor.getString(5);
					String temp_min = mCursor.getString(6);
					String humidity = mCursor.getString(7);
					String description_weather = mCursor.getString(8);

					ObjectWeather objectProject = new ObjectWeather();
					objectProject.setDt_weather(dt);
					objectProject.setDate_city(date_city);
					objectProject.setId(id);
					objectProject.setName_city(name_city);
					objectProject.setIcon_weather(icon_weather);
					objectProject.setTemp(temp);
					objectProject.setTemp_max(temp_max);
					objectProject.setTemp_min(temp_min);
					objectProject.setHumidity(humidity);
					objectProject.setDescription_weather(description_weather);

					arrayProject.add(objectProject);
				} while (mCursor.moveToNext());
			}
			mCursor.close();
			mDataBase.close();
		} catch (Exception e) {
		}
		return arrayProject;
	}
	
	// view info in table weather view
	public ObjectCity getInfoWeatherView() {
		ObjectCity objectCity = new ObjectCity();
		String sql = "SELECT * FROM " + DBDefinition.TABLE_WEATHER_VIEW;
		try {
			openDataBase();
			Cursor mCursor = mDataBase.rawQuery(sql, null);
			if (mCursor != null && mCursor.moveToFirst()) {
				do {
					String name_city = mCursor.getString(2);
					String time_update = mCursor.getString(0);
					objectCity.setName(name_city);
					objectCity.setTime_update(time_update);
				} while (mCursor.moveToNext());
			}
			mCursor.close();
			mDataBase.close();
		} catch (Exception e) {
		}
		return objectCity;
	}	
	
	// view info in table forecast
	public ArrayList<ObjectForecast> getInfoForecast(String name_city_input) {
		ArrayList<ObjectForecast> arrayProject = new ArrayList<ObjectForecast>();
		String sql = "SELECT * FROM '" + DBDefinition.TABLE_FORECAST + "' WHERE name_city = '" + name_city_input+"'";
		try {
			openDataBase();
			Cursor mCursor = mDataBase.rawQuery(sql, null);
			if (mCursor != null && mCursor.moveToFirst()) {
				do {
					String dt = mCursor.getString(0);
					String id = mCursor.getString(1);
					String name_city = mCursor.getString(2);
					String day_of_week = mCursor.getString(3);
					String day_of_month = mCursor.getString(4);
					String icon  = mCursor.getString(5);
					String temp_max  = mCursor.getString(6);
					String temp_min = mCursor.getString(7);
					String id_weather = mCursor.getString(8);

					ObjectForecast objectProject = new ObjectForecast();
					objectProject.setDt_forecast(dt);
					objectProject.setId(id);
					objectProject.setName_city(name_city);
					objectProject.setDay_of_week(day_of_week);
					objectProject.setDay_of_month(day_of_month);
					objectProject.setIcon(icon);
					objectProject.setTemp_max(temp_max);
					objectProject.setTemp_min(temp_min);
					objectProject.setId_weather(id_weather);

					arrayProject.add(objectProject);
				} while (mCursor.moveToNext());
			}
			mCursor.close();
			mDataBase.close();
		} catch (Exception e) {
		}
		return arrayProject;
	}	

	
	@Override
	public synchronized void close() {
		if (mDataBase != null)
			mDataBase.close();
		super.close();
	}
	
	// Copy the database from assets
	private void copyDataBase() throws IOException {
		InputStream mInput = mContext.getAssets().open(
				DBDefinition.DATABASE_NAME);
		String outFileName = DB_PATH + DBDefinition.DATABASE_NAME;
		File createOutFile = new File(outFileName);
		if (!createOutFile.exists()) {
			createOutFile.mkdir();
		}
		OutputStream mOutput = new FileOutputStream(outFileName);
		byte[] mBuffer = new byte[1024];
		int mLength;
		while ((mLength = mInput.read(mBuffer)) > 0) {
			mOutput.write(mBuffer, 0, mLength);
		}
		mOutput.flush();
		mOutput.close();
		mInput.close();
		Log.d("Luong", "============== copy db thanh cong");
	}
	
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}

}
